<?php
/**
 *
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-09-07
 * Time: 21:49
 */

namespace App\Services\Front;

use App\Models\Logistics;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\UserHome;
use App\Models\UserIncomeScoreLog;
use App\Models\UserTeamPriceLog;

class OrderService
{
    //积分到账处理/$all意思为是否自动操作 1是
    public function integralEnter($order, $levelList)
    {
        if (!$order['is_integral'] && ($order['status'] == 5 || $order['status'] == 4)) {
            $userIncomeScoreLogList = UserIncomeScoreLog::select('t1.*')
                ->from((new UserIncomeScoreLog())->getTable() . ' as t1')
                ->join((new OrderDetail())->getTable() . ' as t2', 't1.order_detail_id', '=', 't2.id')
                ->whereIn('t2.is_shouhou', [0, 3])
                ->where(['t1.order_id' => $order['id'], 't1.status' => "WAIT"])
                ->get()
                ->toArray();
            foreach ($userIncomeScoreLogList as $value) {
                $levelIntegral = null;
                $levelShopIntegral = null;
                $lastLevelId = -1;
                UserHome::where(['id' => $value['userId']])->increment("use_integral", $value['score']);
                UserHome::where(['id' => $value['userId']])->increment("add_integral", $value['score']);
                if ($value['source'] == "SHOP") {
                    UserHome::where(['id' => $value['userId']])->increment("shop_integral", $value['score']);
                }
                $user = UserHome::where(['id' => $value['userId']])->lockForUpdate()->first();
                if ($user) {
                    $this->upLevel($levelList, $user);
                }
                UserIncomeScoreLog::where(['incomeScoreLogId' => $value['incomeScoreLogId']])->update([
                    'consumeScore' => $user['use_integral'],
                    'grandScore' => $user['add_integral'],
                    'status' => "ENTER"
                ]);
            }
            $userTeamPriceLog = UserTeamPriceLog::select('t1.*')
                ->from((new UserTeamPriceLog())->getTable() . ' as t1')
                ->join((new OrderDetail())->getTable() . ' as t2', 't1.order_detail_id', '=', 't2.id')
                ->whereIn('t2.is_shouhou', [0, 3])
                ->where(['t1.order_id' => $order['id'], 't1.status' => "WAIT"])
                ->get()
                ->toArray();
            unset($value);
            foreach ($userTeamPriceLog as $value) {
                UserHome::where(['id' => $value['userId']])->increment("consumePrice", $value['price']);
                UserHome::where(['id' => $value['userId']])->increment("grandPrice", $value['price']);
                UserHome::where(['id' => $value['userId']])->increment("lockPrice", -$value['price']);
                $user = UserHome::where(['id' => $value['userId']])->lockForUpdate()->first();
                UserTeamPriceLog::where(['userTeamPriceLogId' => $value['userTeamPriceLogId']])->update([
                    'consumePrice' => $user['consumePrice'],
                    'grandPrice' => $user['grandPrice'],
                    'withdrawPrice' => $user['withdrawPrice'],
                    'status' => "ENTER"
                ]);
            }
        }
    }

    public function upLevel($levelList, $user)
    {
        $levelIntegral = 0;
        $lastLevelId = 0;
        $levelShopIntegral = 0;
        foreach ($levelList as $key => $level) {
            if ($level['levelId'] == ($user['levelId'] + 1)) {
                $levelIntegral = $level['integral'];
                $levelShopIntegral = $level['shop_integral'];
                $lastLevelId = $level['levelId'];
                break;
            }
        }
        if ($levelIntegral && ($lastLevelId > 0) && isset($levelShopIntegral)) {
            if (($user['add_integral'] >= $levelIntegral) && ($user['shop_integral'] >= $levelShopIntegral)) {
                UserHome::where(['id' => $user['id']])->update(['levelId' => $lastLevelId]);
            }
        }
    }

    public function refund($returnPrice, $order, $orderdetail)
    {
        $payType = $order['paytype'];
        if ($order['orderpaytype'] == 1) {
            $paycode = $order['paycode'];
        } else {
            $paycode = $order['ordernum'];
        }
        $orderList = Order::where('paycode',$order['paycode'])->get()->toArray();
        $totalFee = 0;
        foreach ($orderList as $value){
            if($value['oldAllPirce']){
                $totalFee += $value['oldAllPirce'];
            }else{
                $totalFee += $value['allprice'];
            }
        }
        unset($value);
        if ($payType == 1) {//微信退款
            $openid = '';
            $outTradeNo = $paycode;//单号
            $totalFee = $totalFee * 100;//订单总金额，单位为分，只能为整数
            $refundFee = $returnPrice * 100;//退款总金额订单总金额单位为分只能为整数
            // $totalFee = 1;//订单总金额，单位为分，只能为整数
            // $refundFee = 1;//退款总金额订单总金额单位为分只能为整数
            //判断实际退款是否为0
            if ($refundFee > 0) {
                // code...
                $outRefundNo = date("Ymd") . time();
                $WinXinRefund = new WinXinRefund($openid, $outTradeNo, $totalFee, $outRefundNo, $refundFee);
                $result = $WinXinRefund->refund();
                // 更新退款信息
                if ($result['return_code'] == "SUCCESS") {
                    if ($result['result_code'] == "SUCCESS") {
                        OrderDetail::where('id', $orderdetail['id'])->update(['is_shouhou' => 2, 'sjtdkq' => $returnPrice, 'sjtkprice' => $returnPrice]);//2=已完成,3=已拒绝
                        $orderDetailNum = OrderDetail::where('order_id', $order['id'])->where('is_shouhou', '!=', 2)->count();
                        if (!$orderDetailNum) {
                            Order::where('id', $order['id'])->update(['status' => 5, 'is_all_shouhou' => 1, 'is_shouhou' => 2, 'is_xs_sh_anniu' => 2]);
                        } else {
                            $orderDetailNum = OrderDetail::where('order_id', $order['id'])->where('is_shouhou', '!=', 1)->where('is_shouhou != 2')->count();
                            if ($orderDetailNum) {
                                if ($order['status'] == 6) {
                                    $orderDetailNum = OrderDetail::where('order_id', $order['id'])->where('is_shouhou', 1)->count();
                                    if (!$orderDetailNum) {
                                        Order::where('id', $order['id'])->update(['is_shouhou' => 0,'status'=>$order['oldStatus']]);
                                    }else{
                                        Order::where('id', $order['id'])->update(['is_shouhou' => 1,'status'=>$order['oldStatus']]);
                                    }
                                }
                            }
                        }
                        //推送消息
                        $logistics = [
                            'name' => '您的订单号:' . $order['ordernum'] . '已经完成退款,详情已到账为准',
                            'createtime' => time(),
                            'userhome_id' => $order['userhome_id'],
                            'order_id' => $order['id']
                        ];
                        // unset($order['ordernum']);
                        Logistics::insertGetId($logistics);
                        //jpush_stu_single($order['userhome_id'], $logistics['name'], '', 2);//2=订单消息
                    } else {
                        return -1;
                    }
                } else {
                    return -1;
                }
            }
        }
        if ($payType == 2) {//支付宝退款
            $yue_sn = $paycode;
            // dump($paycode);die;
            $out_request_no = time();//部分退款
            // include "./alipay/aop/AopClient.php";
            // include "./alipay/aop/AopCertClient.php";
            // include "./alipay/aop/request/AlipayTradeRefundRequest.php";
            // $c = new \AopCertClient;
            // $appCertPath = "/home/wwwroot/php-zhjz/public/cert/appCertPublicKey_2021002110647757.crt";//应用公钥
            // $alipayCertPath = "/home/wwwroot/php-zhjz/public/cert/alipayCertPublicKey_RSA2.crt";//支付宝公钥
            // $rootCertPath = "/home/wwwroot/php-zhjz/public/cert/alipayRootCert.crt";//支付宝根证书
            // $c->gatewayUrl = "https://openapi.alipay.com/gateway.do";
            // $c->appId = "2021002110647757";
            //支付宝
            include "./aop/AopClient.php";
            include "./aop/AopCertClient.php";
            include "./aop/request/AlipayTradeRefundRequest.php";
            $c = new \AopCertClient;
            $root_path = env("ROOT_PATH");
            $appCertPath = $root_path . "public/zhengshu/appCertPublicKey_2021002182617884.crt";//应用公钥
            $alipayCertPath = $root_path . "public/zhengshu/alipayCertPublicKey_RSA2.crt";//支付宝公钥
            $rootCertPath = $root_path . "public/zhengshu/alipayRootCert.crt";//支付宝根证书
            $c->gatewayUrl = "https://openapi.alipay.com/gateway.do";
            $c->appId = "2021002182617884";
            $c->rsaPrivateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCykKr+nuwgwviNEAEdUD7BomIPSFn25XM7a2dzaBLLwVZbC1AZ6PsCGjDyIeTi/L8WECZ/m251cc05ntBfIlnIawwX8DsnZB7/O8usL21rjVyatUFTzW+gz0v7/H0OAj/503g8jBczWFbnxONmstaAo7VCLQ163qfkEYB3a3uo/jMbm0TmvJ50QKh75uvazlptXBxmqUlEhj1qicpdyhz99cbS/2bn4Ci+5CcY9UIBIlXn/iGCWQ/CvxpXbtKGKUQu9UmdROCcM5D5SmEiSWTBn5Pt5tJzTWqK3h+wxlaArdAvf/YOJUin7GoXgjSguRJ28NXftsmt0vT9Johe+cAxAgMBAAECggEATHpjkjw0u+9ljt0s7QYiasKGpy8AwRsS2H8uxqHrcvMybjoRK5e6cfMPxZS4uHMx0FxIcNz8WTbNhAE+E5DdzVXzzwjn/P4HvJ86o1uIzMi1wdkhyqexSLmgPKOuV+KkzfZBiAUkJqyORCPylVjBQ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c->format = "json";
            $c->charset = "GBK";
            $c->signType = "RSA2";
            //调用getPublicKey从支付宝公钥证书中提取公钥
            $c->alipayrsaPublicKey = $c->getPublicKey($alipayCertPath);
            //是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
            $c->isCheckAlipayPublicCert = true;
            //调用getCertSN获取证书序列号
            $c->appCertSN = $c->getCertSN($appCertPath);
            //调用getRootCertSN获取支付宝根证书序列号
            $c->alipayRootCertSN = $c->getRootCertSN($rootCertPath);
            //判断抵扣券是否大于0
            $refundFee = $returnPrice;
            if ($refundFee > 0) {
                // code...
                $request2 = new \AlipayTradeRefundRequest();
                //SDK已经封装掉了公共参数，这里只需要传入业务参数
                $bizcontent = "{\"out_trade_no\": \"{$yue_sn}\","
                    . "\"refund_amount\": \"$refundFee\","
                    . "\"out_request_no\": \"{$out_request_no}\""
                    . "}";
                $request2->setBizContent($bizcontent);
                $result = $c->execute($request2);
                // dump($result);die;
                $responseNode = str_replace(".", "_", $request2->getApiMethodName()) . "_response";
                $resultCode = $result->$responseNode->code;
                if (!empty($resultCode) && $resultCode == 10000) {
                    OrderDetail::where('id', $orderdetail['id'])->update(['is_shouhou' => 2, 'sjtdkq' => $returnPrice, 'sjtkprice' => $returnPrice]);//2=已完成,3=已拒绝
                    $orderDetailNum = OrderDetail::where('order_id', $order['id'])->where('is_shouhou', '!=', 2)->count();
                    if (!$orderDetailNum) {
                        Order::where('id', $order['id'])->update(['status' => 5, 'is_all_shouhou' => 1, 'is_shouhou' => 2, 'is_xs_sh_anniu' => 2]);
                    } else {
                        $orderDetailNum = OrderDetail::where('order_id', $order['id'])->where('is_shouhou', '!=', 1)->where('is_shouhou != 2')->count();
                        if ($orderDetailNum) {
                            if ($order['status'] == 6) {
                                $orderDetailNum = OrderDetail::where('order_id', $order['id'])->where('is_shouhou', 1)->count();
                                if (!$orderDetailNum) {
                                    Order::where('id', $order['id'])->update(['is_shouhou' => 0,'status'=>$order['oldStatus']]);
                                }else{
                                    Order::where('id', $order['id'])->update(['is_shouhou' => 1,'status'=>$order['oldStatus']]);
                                }
                            }
                        }
                    }
                    //推送消息
                    $logistics = [
                        'name' => '您的订单号:' . $order['ordernum'] . '已经完成退款,详情已到账为准',
                        'createtime' => time(),
                        'userhome_id' => $order['userhome_id'],
                        'order_id' => $order['id']
                    ];
                    // unset($order['ordernum']);
                    Logistics::insertGetId($logistics);
                    //jpush_stu_single($order['userhome_id'], $logistics['name'], '', 2);//2=订单消息
                } else {
                    $sub_msg = $result->$responseNode->sub_msg;
                    return -1;
                }
            }
        }
        return 1;
    }
}